package cn.pzhuweb.controller;

import cn.pzhuweb.model.*;
import cn.pzhuweb.pojo.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//import org.apache.coyote.Request;

/**
 * Servlet implementation class TodoServlet
 */
@WebServlet("/TodoServlet")
public class TodoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public TodoServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		// 1.编码
		request.setCharacterEncoding("utf-8");
		// 2.接受参数
		String xm = request.getParameter("xm");
		String sage = request.getParameter("age");
		String[] hobby = request.getParameterValues("hobby");
		// 3.数据类型转换
		Integer age = 0;
		try {
			age = Integer.parseInt(sage);
		} catch (Exception e) {
			request.getSession().setAttribute("error", "年龄不是数字");
			response.sendRedirect("error.jsp");
			return;
		}
		// 4.封装数据
		SUser user = new SUser(xm, age, hobby);
		// 5.调用模型方法
		Message message = UserUtil.check(user);
		
		@SuppressWarnings("unchecked")
		HashMap<String, SUser> map = (HashMap<String, SUser>) request.getServletContext().getAttribute("map");
		// 6.保存模型的结果
		if (!message.isSuccess()) {
			request.getSession().setAttribute("error", message.getMsg());
			response.sendRedirect("error.jsp");
			return;
		}
		if (!UserUtil.isRegist(xm, map)) {
			request.getSession().setAttribute("error", "用户已被登记");
			response.sendRedirect("error.jsp");
			return;
		}

		HashMap<String, SUser> newmap = UserUtil.add(user, map);
		// 成功，返回到登记成功的页面
		// 7.保存新的map
		request.getServletContext().setAttribute("map", newmap);// 保存所有信息，方便在显示登记表的时候显示
		// 8.定向到seccess.jsp
		request.getSession().setAttribute("user", user);// 保存用户信息，方便在success页面进行显示
		request.getSession().setAttribute("XM", xm);// 保存用户信息，方便在success页面进行显示
		request.getSession().setAttribute("flag", "yes");// 表示用户执行了todo
		response.sendRedirect("success.jsp");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
}
